package com.mzj.saas.commons;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.security.MessageDigest;

/**
 * 
 * @Description
 *   
 * @Author  ???
 * @Date    2018年1月10日下午4:59:58
 * @Version 1.0
 */
public class FileMd5Compare {
	private static final Logger LOG = LoggerFactory.getLogger(FileMd5Compare.class);
	private FileMd5Compare() {
	}

	public static boolean verifyInstallPackage(String packagePath, String crc) {
		String fileSrc = getFileMd5(packagePath);
		String rCrc=crc;
		rCrc = rCrc.toLowerCase();
		boolean flag = false;
		if (rCrc!=null&&fileSrc!=null&&fileSrc.equals(rCrc)) {
			flag = true;
		}
		return flag;
	}
	
	
	public static String getFileMd5(String packagePath){
		return getFileMd5(new File(packagePath));
	}

	public static String getFileMd5(File file){
		String digestStr = "";
		try {
			if (!file.isFile()) {
				return digestStr;
			}
			
			MessageDigest digest = digestOp(file);
			if(digest==null) {
				return digestStr;
			}
			byte[] digestByte = digest.digest();
			digestStr = bytesToHexString(digestByte);
			digestStr = digestStr.toLowerCase();
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			return "";
		}
		return digestStr;
	}

	private static MessageDigest digestOp(File file) {
		int len;
		MessageDigest digest = null;
		byte[] buffer = new byte[1024];
		try (FileInputStream in = new FileInputStream(file)){
			digest = MessageDigest.getInstance("MD5");
			int i = 1024;
			while ((len = in.read(buffer, 0, i)) != -1) {
				digest.update(buffer, 0, len);
			}
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return digest;
	}

	public static String bytesToHexString(byte[] src) {
		StringBuilder stringBuilder = new StringBuilder("");
		if (src == null || src.length <= 0) {
			return stringBuilder.toString();
		}
		int i = 0;
		while (i < src.length) {
			int v;
			String hv;
			v = (src[i] >> 4) & 0x0F;
			hv = Integer.toHexString(v);
			stringBuilder.append(hv);
			v = src[i] & 0x0F;
			hv = Integer.toHexString(v);
			stringBuilder.append(hv);
			i++;
		}
		return stringBuilder.toString();
	}

}
